package com.slipper.bpmn.dealer.support;

import com.slipper.constants.FlowConstants;
import com.slipper.groovy.service.GroovyService;
import com.slipper.bpmn.BpmnEngine;
import com.slipper.system.flow.service.FlowInstNodeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import com.slipper.bpmn.vo.BpmnVO;
import com.slipper.system.flow.bo.FlowInstBO;
import com.slipper.system.flow.bo.FlowInstNodeBO;
import com.slipper.system.flow.bo.FlowNodeBO;
import com.slipper.bpmn.dealer.INodeDealer;

import java.util.HashMap;
import java.util.Map;

/**
 * 脚本节点处理器
 */
@Component
public class ScriptNodeDealer implements INodeDealer {
    @Resource
    private FlowInstNodeService flowInstNodeService;
    @Resource
    private BpmnEngine bpmnEngine;
    
    @Override
    public String[] getTypes() {
        return new String[] { "11" };
    }

    @Override
    public FlowInstNodeBO doDeal(
            int dealCnt,
            boolean finished,
            FlowNodeBO flowNode,
            FlowInstBO flowInst,
            FlowInstNodeBO preInstNode,
            FlowInstNodeBO currInstNode,
            BpmnVO vo) {
        if (currInstNode == null) {
            currInstNode = this.createInstData(flowNode, flowInst, preInstNode, vo);
        } else {
            currInstNode = this.flowInstNodeService.queryBy(currInstNode.getId());
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("flowId", flowNode.getFlowId());
        paramMap.put("currNodeId", flowNode.getId());
        paramMap.put("currInstId", flowInst.getId());
        GroovyService.runById(flowNode.getScriptId(), paramMap);

        currInstNode.setDealStatus(FlowConstants.FlowInstNode.DEAL_STATUS_FINISHED);
        flowInstNodeService.save(currInstNode);
        bpmnEngine.next(dealCnt + 1, flowNode, flowInst, currInstNode);

        return currInstNode;
    }

    public FlowInstNodeBO createInstData(
            FlowNodeBO flowNode,
            FlowInstBO flowInst,
            FlowInstNodeBO preFlowInstNode,
            BpmnVO vo) {
        // 节点实例化
        FlowInstNodeBO flowInstNode = new FlowInstNodeBO();
        flowInstNode.setInstId(flowInst.getId());
        flowInstNode.setPreInstNodeId(preFlowInstNode.getId());
        flowInstNode.setLineId(flowNode.getInLineId());
        flowInstNode.setCurrFlowNodeId(flowNode.getId());
        flowInstNode.setDealManId(vo.getCurrEmpId());
        flowInstNode.setDealOrgId(vo.getCurrOrgId());
        flowInstNode.setStartTime(System.currentTimeMillis());
        flowInstNode.setEndTime(System.currentTimeMillis());
        flowInstNode.setUpdateTime(System.currentTimeMillis());
        flowInstNode.setCreateTime(System.currentTimeMillis());
        flowInstNode.setDealStatus(FlowConstants.FlowInstNode.DEAL_STATUS_PENDING);
        this.flowInstNodeService.save(flowInstNode);
        
        return flowInstNode;
    }
}
